# -*- coding: utf-8 -*-
"""首页下的所有视图函数"""
from flask import current_app, jsonify
from flask import g
from flask import render_template
from flask import request
from flask import session

from info.constants import HOME_PAGE_MAX_NEWS, CLICK_RANK_MAX_NEWS
from info.models import User, News, Category
from info.utills.captcha.response_code import RET
from info.utills.common import check_user_login
from . import index_blue
from info import redis_store


@index_blue.route('/index_news')
def index_news():
    # 首页新闻数据展示
    # 1.获取数据cid,page,per_page
    cid = request.args.get('cid', 1)
    page = request.args.get('page', 1)
    per_page = request.args.get('per_page', HOME_PAGE_MAX_NEWS)
    # 2.校验数据
    try:
        cid = int(cid)
        page = int(page)
        per_page = int(per_page)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数")
    filters = [News.status == 0]
    if cid != 1:
        # 查询的不是最新数据,需要添加分类条件(对象)
        filters.append(News.category_id == cid)
    try:
        paginate = News.query.filter(*filters).order_by(News.create_time.desc()).paginate(page, per_page, False)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据查询错误")

    index_model_list = paginate.items  # 模型对象列表
    current_page = paginate.page
    total_page = paginate.pages
    news_dict = []
    for news in index_model_list:
        news_dict.append(news.to_basic_dict())
    data = {
        'total_page': total_page,
        'current_page': current_page,
        'news_dict': news_dict
    }
    return jsonify(errno=RET.OK, errmsg="OK", data=data)


@index_blue.route('/')
@check_user_login
def index():
    # 首页分类展示
    user = g.user
    categories = Category.query.all()
    cate_list = []
    for cate in categories:
        cate_list.append(cate.to_dict())

    # 点击排行
    news_list = []
    try:
        news_list = News.query.order_by(News.clicks.desc()).limit(CLICK_RANK_MAX_NEWS)
    except Exception as e:
        current_app.logger.error(e)

    news_dict = []
    for news in news_list:
        news_dict.append(news.to_basic_dict())
    # 换用过滤器的方式实现
    # class_dict = {
    #     0: 'first',
    #     1: 'second',
    #     2: 'third'
    # }
    data = {
        "user": user.to_dict() if user else None,
        "news_dict": news_dict,
        'cate_list': cate_list
    }
    return render_template('news/index.html', data=data)


@index_blue.route('/favicon.ico')
# 渲染网页图标
def favicon():
    return current_app.send_static_file('favicon.ico')
